package leetcode.topinterviewquestions;

public class Problem_0141_LinkedListCycle {

    public static boolean hasCycle(ListNode head) {
        return getFirstLoopNode(head) != null;
    }

    public static ListNode getFirstLoopNode(ListNode head) {
        if (head == null || head.next == null || head.next.next == null) {
            return null;
        }
        ListNode slow = head.next;
        ListNode fast = head.next.next;
        while (slow != fast) {
            if (fast.next == null || fast.next.next == null) {
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        fast = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }

    public static class ListNode {
        int val;
        ListNode next;
    }

}
